package com.mingtu.dzpatrol.activity;

import android.content.pm.ApplicationInfo;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.DPoint;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolygonOptions;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.model.Response;

import com.mingtu.dzpatrol.R;
import com.mingtu.dzpatrol.base.BaseActivity;
import com.mingtu.dzpatrol.bean.AreaBean;
import com.mingtu.dzpatrol.bean.VideoListBean2;
import com.mingtu.dzpatrol.callback.StringDialogCallback;
import com.mingtu.dzpatrol.utils.ActivityUtil;
import com.mingtu.dzpatrol.utils.Constant;
import com.mingtu.dzpatrol.utils.IntentUtils;
import com.mingtu.dzpatrol.utils.MarkerOptionsUtils;
import com.mingtu.dzpatrol.utils.MyLogUtil;
import com.mingtu.dzpatrol.utils.MyUtills;
import com.mingtu.dzpatrol.utils.SPTools;
import com.mingtu.dzpatrol.utils.StatusBarUtil;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.mingtu.dzpatrol.utils.Constant.INFO_WINDOW_OFF_SET_Y;
import static com.mingtu.dzpatrol.utils.Constant.MAX_ZOOM;
import static com.mingtu.dzpatrol.utils.MyUtills.getBounds;


public class MonitoringDequiMapActivity extends BaseActivity implements AMap.OnMarkerClickListener,
        AMap.InfoWindowAdapter, AMap.OnInfoWindowClickListener, AMap.OnMapTouchListener {
    @BindView(R.id.mapView)
    MapView mapView;
    @BindView(R.id.iv_location)
    ImageView ivLocation;
    @BindView(R.id.iv_switch)
    ImageView ivSwitch;
    @BindView(R.id.status_bar_view)
    View statusBarView;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    private AMap aMap;
    private List<Marker> markerList = new ArrayList<>();
    private LatLng location;
    private View infoWindow;
    private int position;
    private boolean isSwitch = true;
    private ImmersionBar immersionBar;
    private Marker clickMarker;
    private List<LatLng> areaAllLatLng;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_monitoring_dequi_map;
    }

    @Override
    protected void initView() {
        hideHeadView();
        StatusBarUtil.addStatusBarHeight(statusBarView);
        //沉侵式状态栏
        immersionBar = ImmersionBar.with(this);
        immersionBar.statusBarDarkFont(false);  //状态栏字体是深色，不写默认为亮色
        immersionBar.navigationBarDarkIcon(false);
        immersionBar.init();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void getData() {
        position = getIntent().getIntExtra("position", 404);
    }

    @Override
    protected void initMap(Bundle savedInstanceState) {
        super.initMap(savedInstanceState);
        mapView = findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);
        aMap = mapView.getMap();
        //地图模式可选类型：MAP_TYPE_NORMAL,MAP_TYPE_SATELLITE,MAP_TYPE_NIGHT
        aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 矢量地图模式
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.setMaxZoomLevel(MAX_ZOOM);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(Constant.MAP_ZOOM_TWO));
        aMap.setOnMarkerClickListener(this);
        aMap.setInfoWindowAdapter(this);
        aMap.addOnMapTouchListener(this);
//        aMap.setOnInfoWindowClickListener(this);
        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {
                getDequiList();
                getAreaData();

            }
        });
        String longitude = SPStaticUtils.getString(SPTools.lng);
        String latitude = SPStaticUtils.getString(SPTools.lat);
        if (!StringUtils.isEmpty(longitude) && !StringUtils.isEmpty(latitude)) {
            location = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
            //添加Marker
            MarkerOptions markerOptions = new MarkerOptions()
                    .position(location)
                    .icon(BitmapDescriptorFactory.fromResource(R.mipmap.sb_icon_wz));
            Marker marker = aMap.addMarker(markerOptions);
            markerList.add(marker);
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(location));
        }
    }

    @OnClick({R.id.iv_location, R.id.iv_switch, R.id.iv_back})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                ActivityUtil.removeActivity(this);
                break;
            case R.id.iv_location:
                if (location != null) {
                    aMap.animateCamera(CameraUpdateFactory.changeLatLng(location));
                    aMap.moveCamera(CameraUpdateFactory.zoomTo(Constant.MAP_ZOOM));
                }
                break;
            case R.id.iv_switch:
                if (isSwitch) {
                    isSwitch = false;
                    aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
                    immersionBar.statusBarDarkFont(true);
                    immersionBar.init();
                } else {
                    isSwitch = true;
                    aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 卫星地图模式
                    immersionBar.statusBarDarkFont(false);
                    immersionBar.init();
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (aMap != null) {
            mapView.onDestroy();
        }

        if (markerList.size() > 0) {
            for (Marker marker : markerList) {
                marker.remove();
            }
            markerList.clear();
        }

        super.onDestroy();
    }

    /**
     * 设备信息
     */
    private void getDequiList() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", 1);
        hashMap.put("pageSize", 300);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(Constant.getInstance().POST_CAMERA_LIST)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            VideoListBean2 videoListBean = null;
                            Gson gson = GsonFactory.getSingletonGson();
                            videoListBean = new VideoListBean2();
                            videoListBean = gson.fromJson(result, VideoListBean2.class);
                            List<VideoListBean2.PageBean.ListBean> dataBeans = videoListBean.getPage().getList();

                            if (dataBeans != null) {
                                int size = dataBeans.size();
                                if (size > 0) {
                                    ArrayList<BitmapDescriptor> cameraBayonetGif = new ArrayList<BitmapDescriptor>();
                                    ApplicationInfo appInfo2 = context.getApplicationInfo();
                                    for (int i = 1; i <= 24; i++) {
                                        int resID = getResources().getIdentifier("icon_camera_bayonet" + i, "mipmap", appInfo2.packageName);
                                        cameraBayonetGif.add(BitmapDescriptorFactory.fromResource(resID));
                                    }

                                    List<LatLng> latLngs = new ArrayList<>();

                                    for (int i = 0; i < size; i++) {
                                        VideoListBean2.PageBean.ListBean listBean = dataBeans.get(i);
                                        String latitude = listBean.getLat();
                                        String longitude = listBean.getLng();
                                        String status = listBean.getStatus();
                                        String name = listBean.getName();
                                        String code = listBean.getCode();

                                        if (StringUtils.isEmpty(status)) {
                                            status = "1"; //为空的话 暂时赋值为离线状态
                                        }

                                        //过滤掉经纬度为空的数据
                                        if (!StringUtils.isEmpty(latitude) && !StringUtils.isEmpty(longitude)) {
                                            double lat = Double.parseDouble(latitude);
                                            double lng = Double.parseDouble(longitude);
                                            LatLng location = new LatLng(lat, lng);

                                            HashMap<String, Object> myHashMap = new HashMap<>();
                                            myHashMap.put("cameraName", name);
                                            myHashMap.put("code", code);
                                            String cameraInfo = GsonUtils.toJson(myHashMap);

                                            //添加Marker
                                            if (status.equals("0")) {
                                                Marker marker2 = aMap.addMarker(MarkerOptionsUtils.getMarkerOptions2(location, cameraInfo, INFO_WINDOW_OFF_SET_Y, cameraBayonetGif));
                                                markerList.add(marker2);
                                                latLngs.add(location);

                                            } else if (status.equals("1")) {
                                                Marker marker22 = aMap.addMarker(MarkerOptionsUtils.getMarkerOptions1(location, cameraInfo, INFO_WINDOW_OFF_SET_Y, R.mipmap.icon_camera_bayonet_offline));
                                                markerList.add(marker22);
                                                latLngs.add(location);
                                            }

                                        }

                                        if (latLngs.size() > 0) {
                                            aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(getBounds(latLngs), 300));
                                        }
                                    }


                                }
                            }
                        }
                    }
                });
    }

    @Override
    public View getInfoWindow(Marker marker) {
        //关闭了点击事件，此处逻辑没有展示效果
        if (infoWindow == null) {
            infoWindow = LayoutInflater.from(this).inflate(R.layout.bubble_view2, null);
        }

        List<LatLng> latLngs = new ArrayList<>();
        LatLng latLng = marker.getPosition();
        latLngs.add(latLng);
        latLngs.add(location);
        float distance = MyUtills.getDistance(latLngs);
        if (distance < 1) {
            return null;
        }
        render(marker, infoWindow);
        return infoWindow;

    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    @Override
    public void onInfoWindowClick(Marker marker) {
        marker.hideInfoWindow();
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        marker.showInfoWindow();
        clickMarker = marker;
        return false;
    }

    @Override
    public void onTouch(MotionEvent motionEvent) {
        if (clickMarker != null) {
            boolean b = clickMarker.isInfoWindowShown();
            if (b) {
                clickMarker.hideInfoWindow();
            }
        }
    }

    /**
     * 自定义infowinfow窗口
     */
    public void render(Marker marker, View view) {
        String cameraInfo = marker.getTitle();
        TextView title = ((TextView) view.findViewById(R.id.title));

        JSONObject jsonObject = JSON.parseObject(cameraInfo);
        String code = jsonObject.getString("code");
        String cameraName = jsonObject.getString("cameraName");
        title.setText(cameraName);

        LinearLayout layoutMarker = (LinearLayout) view.findViewById(R.id.layout);
        layoutMarker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //防止点击事件和touch事件冲突，所以采用此种方式跳转
                marker.hideInfoWindow();
                getRtspUrl(code, cameraName);
            }
        });


    }

    /**
     * 根据视频监控编号查询rstp地址
     */
    private void getRtspUrl(String code, String title) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("code", code);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(Constant.getInstance().POST_PREVIEW_URL)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();//{"msg":"success","code":0,"status":"rtsp://123.7.84.20:554/openUrl/9M1VWDu"}
                        if (!StringUtils.isEmpty(result)) {
                            JSONObject jsonObject = JSON.parseObject(result);
                            String msg = jsonObject.getString("msg");
                            if (msg.equals("success")) {
                                String vodeoUrl = jsonObject.getString("status");
                                if (StringUtils.isEmpty(vodeoUrl)) {
                                    ToastUtils.showLong("未获取到视频链接！");
                                    return;
                                }
                                Bundle bundle = new Bundle();
                                bundle.putString("videoUrl", vodeoUrl);
                                bundle.putString("title", title);
                                bundle.putString("code", code);
                                IntentUtils.getInstance().readyGo(ActivityUtil.getTopActivity(), NewPreviewActivity.class, bundle);

                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);

                    }
                });
    }

    /**
     * 区域范围
     */
    private void getAreaData() {
        OkGo.<String>get(Constant.GET_AREA)
                .tag(this)
                .cacheMode(CacheMode.REQUEST_FAILED_READ_CACHE)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        getAreaDataCommon(response);
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        getAreaDataCommon(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);

                    }
                });
    }

    private void getAreaDataCommon(Response<String> response) {
        String result = response.body();
        if (!StringUtils.isEmpty(result)) {
            AreaBean areaBean = null;
            try {
                Gson gson = GsonFactory.getSingletonGson();
                areaBean = new AreaBean();
                areaBean = gson.fromJson(result, AreaBean.class);

                List<AreaBean.FeaturesBean> featuresBeans = areaBean.getFeatures();
                List<List<LatLng>> areaLatLngList = new ArrayList<>(); //存放所有区域的数据
                areaAllLatLng = new ArrayList<>();
                for (int i = 0; i < featuresBeans.size(); i++) {
                    AreaBean.FeaturesBean featuresBean = featuresBeans.get(i);
                    AreaBean.FeaturesBean.PropertiesBeanX propertiesBeanX = featuresBean.getProperties();
                    AreaBean.FeaturesBean.GeometryBean geometryBean = featuresBean.getGeometry();
                    List<List<List<List<Double>>>> coordinates = geometryBean.getCoordinates();
                    List<List<Double>> myList = coordinates.get(0).get(0);
                    List<DPoint> geoFencePoints = new ArrayList<DPoint>();  //存放地里围栏需要的数据
                    List<LatLng> latLngs = new ArrayList<>();//存放单条区域的数据
                    for (int j = 0; j < myList.size(); j++) {
                        List<Double> latLngList = myList.get(j);
                        double gpsLat = latLngList.get(1);
                        double gpsLng = latLngList.get(0);
                        //gps 转高德的经纬度
//                                        double[] latlngs = GPSTransToAMap.transform(gpsLat, gpsLng);
//                                        LatLng latLng = new LatLng(latlngs[0], latlngs[1]);
//                                        points.add(new DPoint(latlngs[0], latlngs[1]));

                        LatLng latLng = new LatLng(gpsLat, gpsLng);
                        latLngs.add(latLng); //将坐标装到数组里
                        geoFencePoints.add(new DPoint(gpsLat, gpsLng));
                        areaAllLatLng.add(latLng);

                    }

                    PolygonOptions polygonOptions = new PolygonOptions();
                    polygonOptions.addAll(latLngs);
                    polygonOptions.strokeWidth(5f);
                    polygonOptions.zIndex(45);
                    String gnfy = propertiesBeanX.getGnfq();

                    switch (gnfy) {
                        case "实验区":
                            polygonOptions.fillColor(context.getResources().getColor(R.color.bg_color_00f2));
                            polygonOptions.strokeColor(context.getResources().getColor(R.color.bg_color_00f));
                            break;
                        case "缓冲区":
                            polygonOptions.fillColor(context.getResources().getColor(R.color.bg_color_fff2));
                            polygonOptions.strokeColor(context.getResources().getColor(R.color.bg_color_ecd));
                            break;
                        case "核心区":
                            polygonOptions.fillColor(context.getResources().getColor(R.color.bg_color_ff02));
                            polygonOptions.strokeColor(context.getResources().getColor(R.color.bg_color_f44));
                            break;
                    }

                    aMap.addPolygon(polygonOptions);
                    areaLatLngList.add(latLngs);

                }

                if (areaAllLatLng.size() > 0) {
                    aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(getBounds(areaAllLatLng), 200));
                }

            } catch (JsonSyntaxException e) {
                e.printStackTrace();
            }

        }
    }


}